package servlet.wxpay;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;
import servlet.wxpay.sdk.MyConfig;
import servlet.wxpay.sdk.WXPay;

public class WxPayOrderQueryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private OrderService orderService = new OrderServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String orderNO = request.getParameter("orderNO");
		Order order = orderService.findByOrderNO(orderNO);
		
		//如果订单状态为1，说明已支付，直接返回SUCCESS
		//否则，去查一下微信后台，看看是否支付成功。
		//如果微信后台的状态为成功，则修改订单状态。
		if (order.getStatus()==1) {
			response.getWriter().print("SUCCESS");
		} else {			
			try {
				MyConfig config = new MyConfig();
		        WXPay wxpay = new WXPay(config);
	
		        Map<String, String> data = new HashMap<String, String>();
		        data.put("out_trade_no", orderNO);
	        
	            Map<String, String> resp = wxpay.orderQuery(data);
	            System.out.println(resp);
	            
	            if ("SUCCESS".equals(resp.get("return_code")) && "SUCCESS".equals(resp.get("result_code"))) {
					if ("SUCCESS".equals(resp.get("trade_state"))) {
						order = orderService.findByOrderNO(orderNO);
						//修改订单
						if (order!=null && order.getStatus()==0) {
    						order.setPayType(2);
    						order.setStatus(1);
    						order.setTrade_no(resp.get("transaction_id"));
    						orderService.updateStatus(order);
    					}
					}
					response.getWriter().print(resp.get("trade_state"));
				} else {
					System.out.println(resp.toString());
					response.getWriter().print(resp.toString());
				}
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
